package com.tom.commonframework.common.refreshview;

import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;

/**
 * Created by Tomleisen on 2016/6/14 0014.
 */
public class XRecyclerView extends RecyclerView {

    private OnScrollToBottomListener mOnScrollToBottomListener;

    @Override
    public boolean isEnabled() {
        return isEnabled;
    }

    public void setIsEnabled(boolean isEnabled) {
        this.isEnabled = isEnabled;
    }

    private boolean isEnabled = true;

    public void setOnScrollToBottomListener(OnScrollToBottomListener mOnScrollToBottomListener) {
        this.mOnScrollToBottomListener = mOnScrollToBottomListener;
    }

    public XRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void onScrollStateChanged(int state) {
        super.onScrollStateChanged(state);
        LayoutManager layoutManager = getLayoutManager();
        int lastVisibleItemPosition;  //最后可见的Item的position的值
        if (layoutManager instanceof GridLayoutManager) {   //网格布局的中lastVisibleItemPosition的取值
            lastVisibleItemPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {//瀑布流布局中lastVisibleItemPosition的取值
            int[] into = new int[((StaggeredGridLayoutManager) layoutManager).getSpanCount()];
            ((StaggeredGridLayoutManager) layoutManager).findLastVisibleItemPositions(into);
            lastVisibleItemPosition = findMax(into);
        } else {   //剩下只有线性布局（listview）中lastVisibleItemPosition的取值
            lastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
        }
        if (layoutManager.getChildCount() > 0 && lastVisibleItemPosition >= layoutManager.getItemCount() - 1 && layoutManager.getItemCount() >= layoutManager.getChildCount()) {
            if (null != mOnScrollToBottomListener && mOnScrollToBottomListener.isScrollToBottom() && isEnabled) {
                if (state == RecyclerView.SCROLL_STATE_IDLE) {
                    mOnScrollToBottomListener.onScrollToBottom();
                }
            }
        }

    }


    interface OnScrollToBottomListener {
        boolean isScrollToBottom();

        void onScrollToBottom();
    }


    //瀑布流里面用到的计算公式
    private int findMax(int[] lastPositions) {
        int max = lastPositions[0];
        for (int value : lastPositions) {
            if (value > max) {
                max = value;
            }
        }
        return max;
    }
}
